<?php
/**
 * Description of PostsController
 *
 * @author luigi.pastore
 * @created  4-mag-2011
 */
class PostsController extends Classes_Controller
{
    public function init()
    {
	$this->model_post	= new Classes_Post();
	$this->model_category	= new Classes_Category;

	$this->layout->categories = $this->model_category->fetchAll();
    }
    
    public function indexAction()
    {
	$this->layout->content = array( 'script' => 'posts/index' );
    }
    
    public function nuovoAction()
    {
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;

	    // Validiamo server-side...
	    $errorMsg = $this->checkFormData( $_POST );
	    
	    // Immagine
	    if( !$errorMsg AND $_FILES['post_image']['name'] != '' )
	    {
		$this->uploader = new Classes_Upload( $_FILES['post_image'] );
		
		$errorMsg = $this->handleImage( null, false );
	    }
	    
	    if( !$errorMsg )
	    {
		# Mapping...
		$data = array(
		    'post_title' => $_POST['post_title'],
		    'post_text' => $_POST['post_text'],
		    'post_tags' => $_POST['post_tags'],
		    'post_createdby' => $this->application->auth->user['user_id'],
		    'post_category' => $_POST['post_category'],
		    'post_published' => $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day'],
		    'post_image_ext' => $this->uploader->file_dst_name_ext
		);
		
		$model = new Classes_Post( $data );

		if( is_numeric( $post_id = $model->save()->post_id ) )
		{
		    if( $this->uploader )
		    {
			$errorMsg = $this->handleImage( $post_id, true );
		    }
		    
		    if( !$errorMsg )
		    {
			// Rimanda alla pagina di conferma...
			$this->layout->forward = 'posts/';

			return $this->layout->content = array( 'script' => 'completed' );
		    }
		}
		else
		{
		    trigger_error( 'Errore Inserimento Post' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'posts/nuovo' );
    }

    public function editAction()
    {
	// Edit
	if( !is_null( $this->getParam( 'id' ) ) )
	{
	    // Fetch
	    $post = $this->model_post->fetchById( (int) $this->getParam( 'id' ) );

	    // Se non c'è il post lancia l'errore
	    if( !is_array( $post ) )
	    {
		trigger_error( 'Errore Edit Post', E_USER_WARNING );
	    }
	    else
	    {
		# Format Data
		list( $post['day'], $post['month'], $post['year'] ) = explode( '-', $post['post_published'] );
		
		# Assegniamo i dati del post al layout
		$this->layout->data = $post;
	    }
	}
	
	if( $_POST['salva'] AND $_POST['salva'] !== '' )
	{
	    $this->layout->data = $_POST;

	    // Validiamo server-side...
	    $errorMsg = $this->checkFormData( $_POST );
	    
	    // Immagine
	    if( !$errorMsg AND $_FILES['post_image']['name'] != '' )
	    {
		$this->uploader = new Classes_Upload( $_FILES['post_image'] );
		
		$errorMsg = $this->handleImage( null, false );
	    }
	    
	    if( !$errorMsg )
	    {

		$data = array(
		    'post_id' => $post['post_id'],
		    'post_title' => $_POST['post_title'],
		    'post_text' => $_POST['post_text'],
		    'post_tags' => $_POST['post_tags'],
		    'post_modifiedby' => $this->application->auth->user['user_id'],
		    'post_category' => $_POST['post_category'],
		    'post_published' => $_POST['year'] . '-' . $_POST['month'] . '-' . $_POST['day']
		);

		
		// Se è stata caricata un'immagine aggiorna, altrimenti no...
		if( $this->uploader )
		    $data['post_image_ext'] = $this->uploader->file_dst_name_ext;
		else
		    $data['post_image_ext'] = $post['post_image_ext'];
		
		$model = new Classes_Post( $data );

		if( is_numeric( $post_id = $model->save()->post_id ) )
		{
		    if( $this->uploader )
		    {
			$errorMsg = $this->handleImage( $post_id, true );
		    }
		    
		    if( !$errorMsg )
		    {
			// Rimanda alla pagina di conferma...
			$this->layout->forward = 'posts/';

			return $this->layout->content = array( 'script' => 'completed' );
		    }
		}
		else
		{
		    trigger_error( 'Errore Inserimento Post' );
		}
	    }
	}

	$this->layout->errorMsg = $errorMsg;
	$this->layout->content = array( 'script' => 'posts/edit' );
    }
    
    public function archivioAction()
    {
	$this->layout->posts = $this->model_post->fetchAll();
	$this->layout->content = array( 'script' => 'posts/archivio' );
    }
    
    private function checkFormData( $data )
    {
	if( !filter_var( $_POST['post_title'], FILTER_SANITIZE_STRING ) )
	    $errorMsg['post_title'] = sprintf( ERR_FORMAT, 'Titolo' );

	if( !filter_var( $_POST['post_text'], FILTER_SANITIZE_SPECIAL_CHARS ) )
	    $errorMsg['post_text'] = ERR_EMPTY;

	if( !checkdate( $_POST['month'], $_POST['day'], $_POST['year'] ) )
	    $errorMsg['post_published'] = ERR_DATE;

	return $errorMsg ? $errorMsg : false;
    }
    
    private function handleImage( $post_id, $process = false )
    {
	if( $this->uploader->uploaded )
	{
	    // L'immagine è stata caricata correttamente...
	    $this->uploader->allowed = array( 'image/*' );
	    $this->uploader->image_min_width = 100;
	    $this->uploader->file_safe_name = false;
	    $this->uploader->file_auto_rename = false;
	    $this->uploader->file_overwrite = true;
	    $this->uploader->jpeg_quality = 72;

	    if( $this->uploader->image_src_x > 190 )
	    {
		$this->uploader->image_resize = true;
		$this->uploader->image_x = 190;
		$this->uploader->image_ratio_y = true;
	    }

	    // Processa
	    if( $process === true )
	    {
		// Rinomina e carica...
		$this->uploader->file_new_name_body = 'post_' . $post_id;
		$this->uploader->process( UPLOAD_DIR .'/posts/' );

		if( $this->uploader AND !$this->uploader->processed )
		{
		    // Aggiungi l'errore
		    $errorMsg['post_image'] = $this->uploader->error;
		}
			
		$this->uploader->clean();
	    }
	    else
	    {
		$this->uploader->process();
	    }

	    // Tutto ok?
	    if( !$this->uploader->processed )
	    {
		# Aggiungi l'errore
		$errorMsg['post_image'] = $this->uploader->error;
	    }
	}
	else
	{
	    // Aggiungi l'errore
	    $errorMsg['post_image'] = $this->uploader->error;	    
	}
	
	return $errorMsg ? $errorMsg : false;
    }    
}
